import {
  LockOutlined,
  MobileOutlined,
} from "@ant-design/icons";
import {
  LoginFormPage,
  ProConfigProvider,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from "@ant-design/pro-components";
import {  message, Tabs, theme } from "antd";

import style from "./index.module.less";
import { useMutation } from "@apollo/client";
import { LOGIN, SEND_CODE_MSG } from "@/graphql/auth";
import { AUTH_TOKEN } from "@/utils/contants";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useTitle } from "@/hooks";
import { useUserContext } from "@/hooks/userHooks";



interface IValue{
  tel: string;
  code: string;
  autoLogin: boolean;
}


const Page = () => {
  const { token } = theme.useToken();
  const [run] = useMutation(SEND_CODE_MSG)
  const [login] = useMutation(LOGIN)
  const nav = useNavigate();

  const [params]=useSearchParams()
  const {store}= useUserContext()


  useTitle('登录')
  const loginHandler = async (value:IValue)=>{
    const res = await login({
      variables:value
    })
    // console.log('res',res)
    if(res?.data?.login?.code===200){
      
      // await (store as Store).refetchHandler(); //好像进入了一个奇怪循环？？？导致无法登录
      if(value.autoLogin){
        sessionStorage.setItem(AUTH_TOKEN, '')
        localStorage.setItem(AUTH_TOKEN, res?.data?.login?.data)
      }
      else{
        localStorage.setItem(AUTH_TOKEN, '')
        sessionStorage.setItem(AUTH_TOKEN, res?.data?.login?.data)
      }
      console.log(store)
      if(!store.id){
        if(store.refetchHandler)
          await store.refetchHandler();
      }
      message.success(res.data.login?.message)
      // nav('/')
      nav(params.get('orgUrl')||'/home')
      return
    }
    message.error(res?.data?.login?.message)
  }
  return (
    <div
      className={style.container}
    >
      <LoginFormPage
      initialValues={{tel:'13600001111'}}
        onFinish={loginHandler}
        backgroundImageUrl="https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp"
        logo="https://water-drop-smartoldhu.oss-cn-hangzhou.aliyuncs.com/2a436dfd4bea8778808b237a6fe6190d.jpeg"
      >
        <Tabs
          centered
          items={[{key:'phone', label:"手机号登录"}]}
        >
          {/* <Tabs.TabPane key={'phone'} tab={'手机号登录'} /> */}
        </Tabs>
        <>
          <ProFormText
            fieldProps={{
              size: "large",
              prefix: (
                <MobileOutlined
                  style={{
                    color: token.colorText,
                  }}
                  className={"prefixIcon"}
                />
              ),
            }}
            name="tel"
            placeholder={"手机号"}
            rules={[
              {
                required: true,
                message: "请输入手机号！",
              },
              {
                pattern: /^1\d{10}$/,
                message: "手机号格式错误！",
              },
            ]}
          />
          <ProFormCaptcha
            fieldProps={{
              size: "large",
              prefix: (
                <LockOutlined
                  style={{
                    color: token.colorText,
                  }}
                  className={"prefixIcon"}
                />
              ),
            }}
            captchaProps={{
              size: "large",
            }}
            placeholder={"请输入验证码"}
            captchaTextRender={(timing, count) => {
              if (timing) {
                return `${count} ${"获取验证码"}`;
              }
              return "获取验证码";
            }}
            phoneName="tel"
            name="code"
            rules={[
              {
                required: true,
                message: "请输入验证码！",
              },
            ]}
            onGetCaptcha={async (tel:string) => {
                const res = await run({
                  variables:{
                    tel,
                  }
                })
                if(res?.data?.sendCodeMsg?.code === 200){
                  message.success(res?.data?.sendCodeMsg?.message);
                }else{
                  message.error(res?.data?.sendCodeMsg?.message)
                }
              
            }}
          />
        </>
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>
          <a
            style={{
              float: "right",
            }}
          >
            忘记密码
          </a>
        </div>
      </LoginFormPage>
    </div>
  );
};

const Login = () => {
  return (
    <ProConfigProvider >
      <Page />
    </ProConfigProvider>
  );
};
export default Login;

